<template>
  <div class="layout">
    <loading :state="loading"></loading>
    <cell-edit-text text-left="收货人名称" text-hint="点击输入" :text-default=user :inputText=user @blur="nameVerify"/>
    <div class="space"></div>
    <cell-edit-text text-left="手机号" text-hint="点击输入" :text-default=phone :inputText="phone" @blur="phoneVerify"
                    typeNumber="number"/>
    <div class="space"></div>
    <div class="area">
      <span class="where">所在地区</span>
      <div @click="chooseArea" class="choose">
        <span>{{province + city + area}}</span>
      </div>
    </div>
    <div class="space"></div>
    <cell-edit-text text-left="详细地址" text-hint="点击输入详细地址" :text-default=detail :inputText="detail" @blur="Detail"/>
    <div class="space"></div>
    <div class="edit">
      <span class="editText" @click="deleteAddress()">删除地址</span>
    </div>
    <div class="space"></div>
    <div class="edit">
      <span class="editText" @click="setDefault()">设为默认</span>
    </div>
    <area-choose num="3" ref="areashow" v-on:getArea="getAreaData"/>
    <div class="button">
      <div class="primary" @click="toAddressSure()">确认</div>
      <!--<div class="reverse" @click="setDefault()">设为默认</div>-->
    </div>
  </div>
</template>

<script>
  import CellEditText from '../../components/user/CellEditText';
  import Cell from '../../components/user/Cell';
  import CellTextArea from '../../components/common/CellTextArea';
  import areaChoose from '../../components/common/areaChoose';
  import {Toast} from 'vant';

  export default {
    name: 'edit-address',
    components: {areaChoose, CellTextArea, CellEditText, Cell},
    data() {
      return {
        user: '',
        phone: '',
        detail: '',
        sendMap: 'http://dncake.oss-cn-hangzhou.aliyuncs.com/user/img/sendarea.jpg',
        type: '',
        id: '',
        province: '', // 省
        city: '', // 市
        area: '', // 区
        loading: true,
        showImg: false,
        imgSrc: ''
      };
    },
    methods: {
      Detail(data) {
        let isDe = isChinese(data);
        console.log('isDetail:', isDe, data);
        if (isDe) {
          this.detail = data;
        } else {
          this.$toast({
            message: '详细地址长度不小于5且不包括特殊字符',
            duration: 500
          });
          this.detail = '';
        }
      },
      chooseArea() {
        this.$refs.areashow.changeShow();
      },
      getAreaData(data) {
        this.$nextTick(function () {
          this.province = data.province;
          this.city = data.city;
          this.area = data.county;
        });
      },
      nameVerify(name) {
        let isCh = isChinese(name);
        console.log('isChinese:', isCh);
        if (isCh) {
          this.user = name;
        } else {
          this.$toast({
            message: '请填写正确的姓名!',
            duration: 500
          });
          this.user = '';
        }
      },
      phoneVerify(phone) {
        let isPhone = isMobile(phone);
        console.log('isPhone:', isPhone);
        if (isPhone) {
          this.phone = phone;
        } else {
          this.$toast({
            message: '手机号码不正确!',
            duration: 500
          });
          this.phone = '';
        }
      },
      toAddressSure() {
        let data = {};
        if (this.user === '') {
          Toast('请填写收货人');
        } else if (this.phone === '') {
          Toast('请填写手机号');
        } else if (this.detail === '') {
          Toast('请填写详细地址');
        } else if (this.province === '' || this.city === '' || this.area === '') {
          Toast('省市区未选择');
        } else {
          data.user = this.user;
          data.phone = this.phone;
          data.province = this.province;
          data.city = this.city;
          data.area = this.area;
          data.detail = this.detail;
          data.id = this.id;
          // data.isDefault = 0;
          console.log('address--add-++data-', this.$store.state, data);
          this.loading = true;
          this.$UserReq.address(this.type, data).then(res => {
            console.log('address--add--', res);
            this.loading = false;
            this.$router.push({name: 'userAddress'});
          }, () => {
            this.loading = false;
          });
        }
      },
      setDefault() {
        this.loading = true;
        let data = {
          id: this.id,
          method: 'setDefault'
        };
        if (this.isDefault === 0) { // 改后会影响空提交
          this.$UserReq.address('base', data).then(res => {
            console.log('ress:', res, data);
            // this.loading = false;
            // this.address.forEach((item) => {
            //   item.isDefault = '0';
            // });
            this.isDefault = 1;
            this.$router.push({name: 'userAddress'});
            this.loading = false;
          }, () => {
            this.loading = false;
          });
        } else {
          this.loading = false;
          if (this.isDefault === 1) {
            this.$router.push({name: 'userAddress'});
          } else {
            Toast('请先添加地址');
          }
        }
      },
      deleteAddress() {
        if (this.id) {
          if (this.isDefault === 1) {
            Toast('默认地址不可删除');
          } else {
            this.loading = true;
            let data = {
              id: this.id,
              method: 'delete'
            };
            this.$UserReq.address('delete', data).then(res => {
              console.log('deletedeletedelete:', res);
              this.loading = false;
              this.$router.go(-1);
              // this.address = this.address.filter(t => t.id !== data.id);
            }, () => {
              this.loading = false;
            });
          }
        } else {
          Toast('请先添加地址');
        }
      }
    },
    computed: {},
    watch: {
      // 监听具体数据变化，并做相应的处理
    },
    beforeCreate() {
      // 可以在这加个loading事件，在加载实例时触发
      // 这个阶段实例的data、methods是读不到的
    },
    created() {
      let address = this.$route.query;
      this.loading = false;
      if (address.name) {
        this.user = address.name;
        this.phone = address.phone;
        this.province = address.province;
        this.city = address.city;
        this.area = address.area;
        this.detail = address.detail;
        this.type = 'update';
        this.id = address.id;
        this.isDefault = address.isDefault;
        console.log(this.$route.query);
      } else {
        this.type = 'create';
      }
      // 初始化数据，如在这结束loading事件，异步ajax请求也适宜在这里调用
      // 实例创建后：这个阶段已经完成了数据观测(data observer)，属性和方法的运算， watch/event 事件回调。
      // mount挂载阶段还没开始，"el" 属性目前不可见，数据并没有在DOM元素上进行渲染
    }
  };

  // 验证是否含有特殊符号
  function isChinese(str) {
    let regu = /^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$/;
    let re = new RegExp(regu);
    if (re.test(str)) {
      return true;
    } else {
      return false;
    }
  }

  // 验证手机号码
  function isMobile(s) {
    let regu = /^(13[0-9]|15[0-9]|18[0-9]|147|145|149|170|171|173|175|176|177|178)\d{8}$/;
    if (regu.test(s)) {
      return true;
    } else {
      return false;
    }
  }

  // 验证是否含有特殊符号及长度
  // function isDetail (str) {
  //   let regu = /^[a-zA-Z0-9\u4e00-\u9fa5]$/;
  //   let re = new RegExp(regu);
  //   if (re.test(str)) {
  //     return true;
  //   } else {
  //     return false;
  //   }
  // }

</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  @import "../../assets/stylus/main.styl"
  .layout
    width vw(375)
    height vw(667)
    font-family: PingFangSC-Regular
    margin vw(15)
    word-vw(14, first-ash)

  .space
    space()

  .area
    flex-x(space-between)
    font-size word14
    background-color #fff
    height vw(40)
    border-radius vw(5)
    line-height vw(40)
    margin-top vw(5)
    box-sizing border-box
    width: 92vw;
    .choose
      flex-x(flex-end)
      flex 1
      color #999
      height vw(40)
      span
        margin-right 10px
        color #000

  .where
    flex 1
    font-size word14
    color first-ash
    line-height vw(20)
    height vw(20)
    margin-left vw(10)

  .default
    position absolute
    //word-vw(14, main-color)
    font-size word14
    color main-color
    line-height vw(20)
    height vw(20)
    right vw(25)

  .edit
    background white
    height 11.8vw
    width vw(345)
    border-radius vw(5)

  .editText
    position absolute
    margin-top vw(13)
    margin-left vw(145)
    word-vw(14, main-color)
    height vw(20)
    line-height vw(20)

  .send
    left: vw(15)
    width vw(345)
    height vw(132)

  .button
    position fixed
    z-index 1000
    margin-left vw(-15)
    bottom vw(0)
    width vw(375)
    height vw(50)
    background-color white
    flex-x()

  .primary
    margin auto
    width vw(120)
    height vw(40)
    border-radius vw(100)
    background-color main-color
    align-items center
    justify-content center
    display flex
    display -webkit-flex /* 新版本语法: Chrome 21+ */
    word-vw(16, white)

  .reverse
    position absolute
    margin-left vw(210)
    width vw(120)
    height vw(40)
    border-radius vw(100)
    align-items center
    justify-content center
    display flex
    flex-direction column
    display -webkit-flex /* 新版本语法: Chrome 21+ */
    word-vw(16, main-color)
    border(main-color)
    box-sizing border-box

  //btn-reverse()
</style>
